<template>
  <div class="student-profile-container">
    <!-- 页面标题 -->
    <div class="page-title">学生个人信息中心</div>
    
    <!-- 时间筛选控件 -->
    <div class="time-filter">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="handleDateChange"
        format="YYYY-MM-DD HH:mm:ss"
        value-format="YYYY-MM-DD HH:mm:ss"
      ></el-date-picker>
      <div class="time-buttons">
        <el-button 
          type="primary" 
          size="mini" 
          :class="{ 'active': currentTimeRange === 'week' }"
          @click="handleQuickDateClick('week')"
        >
          本周
        </el-button>
        <el-button 
          type="primary" 
          size="mini" 
          :class="{ 'active': currentTimeRange === 'month' }"
          @click="handleQuickDateClick('month')"
        >
          本月
        </el-button>
        <el-button 
          type="primary" 
          size="mini" 
          :class="{ 'active': currentTimeRange === 'quarter' }"
          @click="handleQuickDateClick('quarter')"
        >
          本季度
        </el-button>
        <el-button 
          type="primary" 
          size="mini" 
          :class="{ 'active': currentTimeRange === 'year' }"
          @click="handleQuickDateClick('year')"
        >
          本年
        </el-button>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <el-loading 
      v-if="loading" 
      fullscreen 
      text="正在加载数据，请稍候..."
    ></el-loading>
    
    <!-- 错误提示 -->
    <el-alert
      v-if="errorMsg"
      title="数据加载失败"
      :description="errorMsg"
      type="error"
      show-icon
      closable
      @close="errorMsg = ''"
    ></el-alert>

    <el-row :gutter="20">
      <!-- 左侧：个人信息卡片 -->
      <el-col :span="6">
        <el-card class="profile-card">
          <div slot="header">
            <span>个人基本信息</span>
          </div>
          <div class="profile-info">
            <div class="avatar-container">
              <el-avatar :size="100" class="avatar">
                {{ studentInfo.student_name?.slice(0, 1) || '学' }}
              </el-avatar>
            </div>
            
            <div class="info-item">
              <span class="label">姓名：</span>
              <span class="value">{{ studentInfo.student_name || '加载中...' }}</span>
            </div>
            
            <div class="info-item">
              <span class="label">账号：</span>
              <span class="value">{{ studentInfo.username || '加载中...' }}</span>
            </div>
            
            <div class="info-item">
              <span class="label">学号：</span>
              <span class="value">{{ studentInfo.student_id || '加载中...' }}</span>
            </div>
            
            <div class="info-item">
              <span class="label">年级班级：</span>
              <span class="value" v-if="studentInfo.class_name && studentInfo.grade">
                {{ `${studentInfo.grade}年级${studentInfo.class_name}` }}
              </span>
              <span class="value" v-else>'加载中...'</span>
            </div>
            
            <div class="info-item">
              <span class="label">班级排名：</span>
              <span class="value">{{ studentInfo.class_rank !== null ? studentInfo.class_rank : '暂无' }}</span>
            </div>
            
            <div class="info-item">
              <span class="label">积分：</span>
              <span class="value performance-points">{{ studentInfo.performance_points || 0 }}</span>
            </div>
            
            <div class="info-item">
              <span class="label">待完成考试：</span>
              <span class="value">{{ studentInfo.pending_exams_count || 0 }}</span>
            </div>
          </div>
        </el-card>
        
        <!-- 小组信息卡片 -->
        <el-card class="group-card">
          <div slot="header">
            <span>小组信息</span>
          </div>
          <div v-if="!studentInfo.group_name" class="no-group">
            尚未加入任何小组
          </div>
          <div v-else class="group-info">
            <div class="info-item">
              <span class="label">小组名称：</span>
              <span class="value">{{ studentInfo.group_name }}</span>
            </div>
            
            <div class="info-item">
              <span class="label">小组积分：</span>
              <span class="value">{{ studentInfo.group_total_points || 0 }}</span>
            </div>
            
            <div class="info-item">
              <span class="label">小组排名：</span>
              <span class="value">{{ studentInfo.group_rank !== null ? studentInfo.group_rank : '暂无' }}</span>
            </div>
            
            <el-divider>小组成员</el-divider>
            
            <div class="group-members">
              <div v-for="member in groupMembers" :key="member.student_id" class="member-item">
                <div class="member-info">
                  <span class="member-name">{{ member.name }}</span>
                  <span class="member-id">学号: {{ member.student_number }}</span>
                </div>
                <el-tag v-if="member.is_leader" size="mini" type="success">组长</el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧：数据统计和图表 -->
      <el-col :span="18">
        <!-- 积分理由占比图表 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card">
              <div slot="header">
                <span>个人加分理由占比</span>
              </div>
              <div class="chart-container">
                <div id="personalAddChart" class="chart"></div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <div slot="header">
                <span>个人扣分理由占比</span>
              </div>
              <div class="chart-container">
                <div id="personalMinusChart" class="chart"></div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <el-card class="chart-card">
              <div slot="header">
                <span>小组加分理由占比</span>
              </div>
              <div class="chart-container">
                <div id="groupAddChart" class="chart"></div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <div slot="header">
                <span>小组扣分理由占比</span>
              </div>
              <div class="chart-container">
                <div id="groupMinusChart" class="chart"></div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <!-- 考试成绩图表 -->
        <el-card class="chart-card" style="margin-top: 20px;">
          <div slot="header">
            <span>考试成绩统计</span>
          </div>
          <div class="exam-chart-container">
            <div id="examScoresChart" class="chart" ></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { getStudentInfo, type StudentInfoResponse } from '../../api/user';
import { getGroupMembers, type GroupMembersResponse } from '../../api/group';
import { getStatistics, type StatisticsResponse } from '../../api/point';
import { listExams, type ExamItem } from '../../api/exam';
import * as echarts from 'echarts';

// 状态变量
const loading = ref(true);
const errorMsg = ref('');
const studentInfo = ref<Partial<StudentInfoResponse['content']>>({});
const groupMembers = ref<GroupMembersResponse['content']>([]);
const personalStats = ref<StatisticsResponse['content'] | null>(null);
const groupStats = ref<StatisticsResponse['content'] | null>(null);
const examList = ref<(ExamItem & {class_rank?: number, grade_rank?: number})[]>([]);

// 时间筛选相关
const dateRange = ref<string[]>([]);
const currentTimeRange = ref(''); // 默认本周

// 初始化图表实例
let personalAddChart: echarts.ECharts | null = null;
let personalMinusChart: echarts.ECharts | null = null;
let groupAddChart: echarts.ECharts | null = null;
let groupMinusChart: echarts.ECharts | null = null;
let examScoresChart: echarts.ECharts | null = null;

// 设置时间范围
const setTimeRange = (range: 'week' | 'month' | 'quarter' | 'year') => {
  const end = new Date();
  end.setHours(23, 59, 59, 999);
  
  const start = new Date();
  
  switch (range) {
    case 'week':
      // 自然周：周一到周日（本周一 00:00:00 到本周日 23:59:59）
      const day = start.getDay() || 7; // 转换为周一为1，周日为7
      start.setDate(start.getDate() - (day - 1)); // 回退到本周一
      start.setHours(0, 0, 0, 0);
      
      // 结束日期为本周日
      const sunday = new Date(start);
      sunday.setDate(start.getDate() + 6);
      end.setTime(sunday.getTime());
      end.setHours(23, 59, 59, 999);
      break;
      
    case 'month':
      // 自然月：本月1号 00:00:00 到本月最后一天 23:59:59
      start.setDate(1); // 本月1号
      start.setHours(0, 0, 0, 0);
      
      // 本月最后一天
      const lastDay = new Date(start.getFullYear(), start.getMonth() + 1, 0);
      end.setTime(lastDay.getTime());
      end.setHours(23, 59, 59, 999);
      break;
      
    case 'quarter':
      // 自然季度：季度第一天到季度最后一天
      const month = start.getMonth();
      const quarterStartMonth = Math.floor(month / 3) * 3; // 0, 3, 6, 9
      
      // 季度第一天（如Q4为10月1日）
      start.setMonth(quarterStartMonth);
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      
      // 季度最后一天（如Q4为12月31日）
      const quarterEndMonth = quarterStartMonth + 2;
      const quarterLastDay = new Date(start.getFullYear(), quarterEndMonth + 1, 0);
      end.setTime(quarterLastDay.getTime());
      end.setHours(23, 59, 59, 999);
      break;
      
    case 'year':
      // 自然年：1月1日 00:00:00 到12月31日 23:59:59
      start.setMonth(0); // 1月
      start.setDate(1); // 1号
      start.setHours(0, 0, 0, 0);
      
      // 12月最后一天
      const yearLastDay = new Date(start.getFullYear(), 12, 0);
      end.setTime(yearLastDay.getTime());
      end.setHours(23, 59, 59, 999);
      break;
  }
  
  // 格式化时间为 "YYYY-MM-DD HH:mm:ss"
  const format = (date: Date) => {
    return date.toISOString().slice(0, 19).replace('T', ' ');
  };
  
  // 调整为东八区
  start.setHours(start.getHours() + 8);
  end.setHours(end.getHours() + 8);

  return [format(start), format(end)];
};

// 处理点击快捷日期
const handleQuickDateClick = (type: 'week' | 'month' | 'quarter' | 'year') => {
    currentTimeRange.value = type;
    dateRange.value = setTimeRange(type);
}

// 处理日期变化
const handleDateChange = () => {
  if (dateRange.value.length === 2) {
    currentTimeRange.value = '';
  }
};

// 根据日期范围获取数据
const fetchDataByDateRange = async () => {
  if (!dateRange.value || dateRange.value.length !== 2) return;
  
  const [startTime, endTime] = dateRange.value;
  loading.value = true;
  
  try {
    // 获取个人积分统计
    if (studentInfo.value.student_id) {
      const studentStatsRes = await getStatistics({
        student_id: Number(studentInfo.value.student_id),
        start_time: startTime,
        end_time: endTime
      });
      personalStats.value = studentStatsRes.content;
    }
    
    // 获取小组积分统计
    if (studentInfo.value.group_id) {
      const groupStatsRes = await getStatistics({
        group_id: studentInfo.value.group_id,
        start_time: startTime,
        end_time: endTime
      });
      groupStats.value = groupStatsRes.content;
    }
    
    // 获取考试列表
    examList.value = [];
    const examsRes = await listExams({
      start_time: startTime,
      end_time: endTime
    });
    if (examsRes.code == 200 && examsRes.code == 200) {
        examList.value = examsRes.content;
    }
    // 更新图表
    updateCharts();
  } catch (err) {
    console.error('获取数据失败:', err);
    errorMsg.value = '获取统计数据失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

// 初始化图表
const initCharts = () => {
  // 个人加分图表
  personalAddChart = echarts.init(document.getElementById('personalAddChart')!);
  // 个人扣分图表
  personalMinusChart = echarts.init(document.getElementById('personalMinusChart')!);
  // 小组加分图表
  groupAddChart = echarts.init(document.getElementById('groupAddChart')!);
  // 小组扣分图表
  groupMinusChart = echarts.init(document.getElementById('groupMinusChart')!);
  // 考试成绩图表
  examScoresChart = echarts.init(document.getElementById('examScoresChart')!);
  
  // 窗口大小变化时重绘图表
  window.addEventListener('resize', () => {
    personalAddChart?.resize();
    personalMinusChart?.resize();
    groupAddChart?.resize();
    groupMinusChart?.resize();
    examScoresChart?.resize();
  });
};

// 更新图表数据
const updateCharts = () => {
  // 个人加分理由图表
  if (personalAddChart && personalStats.value) {
    const addReasons = personalStats.value.add_reasons || [];
    personalAddChart.setOption({
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        formatter: function(name: string) {
          const reason = addReasons.find(r => r.reason === name);
          return `${name} (${reason?.points || 0}) ${reason?.personal_percentage || 0}%`;
        }
      },
      series: [
        {
          name: '加分理由',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: addReasons.map(reason => ({
            name: reason.reason,
            value: Math.abs(parseInt(reason.points))
          }))
        }
      ]
    });
  }
  
  // 个人扣分理由图表
  if (personalMinusChart && personalStats.value) {
    const minusReasons = personalStats.value.minus_reasons || [];
    personalMinusChart.setOption({
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        formatter: function(name: string) {
          const reason = minusReasons.find(r => r.reason === name);
          return `${name} (${reason?.points || 0}) ${reason?.personal_percentage || 0}%`;
        }
      },
      series: [
        {
          name: '扣分理由',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: minusReasons.map(reason => ({
            name: reason.reason,
            value: Math.abs(parseInt(reason.points))
          }))
        }
      ]
    });
  }
  
  // 小组加分理由图表
  if (groupAddChart && groupStats.value) {
    const addReasons = groupStats.value.add_reasons || [];
    groupAddChart.setOption({
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        formatter: function(name: string) {
          const reason = addReasons.find(r => r.reason === name);
          return `${name} (${reason?.points || 0}) ${reason?.group_percentage || 0}%`;
        }
      },
      series: [
        {
          name: '加分理由',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: addReasons.map(reason => ({
            name: reason.reason,
            value: Math.abs(parseInt(reason.points))
          }))
        }
      ]
    });
  }
  
  // 小组扣分理由图表
  if (groupMinusChart && groupStats.value) {
    const minusReasons = groupStats.value.minus_reasons || [];
    groupMinusChart.setOption({
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        formatter: function(name: string) {
          const reason = minusReasons.find(r => r.reason === name);
          return `${name} (${reason?.points || 0}) ${reason?.group_percentage|| 0}%`;
        }
      },
      series: [
        {
          name: '扣分理由',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: minusReasons.map(reason => ({
            name: reason.reason,
            value: Math.abs(parseInt(reason.points))
          }))
        }
      ]
    });
  }
  
  // 考试成绩柱状图
  if (examScoresChart) {
    examScoresChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: examList.value.map(item => item.name),
        axisLabel: {
          rotate: 30,
          interval: 0
        }
      },
      yAxis: {
        type: 'value',
        name: '分数',
        min: 0,
        max: 150
      },
      series: [
        {
          name: '考试成绩',
          type: 'bar',
          data: examList.value.map(item => item.score || 0),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#4158D0' },
              { offset: 0.5, color: '#C850C0' },
              { offset: 1, color: '#FFCC70' }
            ])
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#4158D0' },
                { offset: 0.5, color: '#C850C0' },
                { offset: 1, color: '#FFCC70' }
              ])
            }
          }
        }
      ]
    });
  }
};

// 初始化数据
const initData = async () => {
  try {
    // 获取学生基本信息
    const studentRes = await getStudentInfo();
    studentInfo.value = studentRes.content;
    
    // 获取小组成员
    if (studentInfo.value.group_id) {
      const groupMembersRes = await getGroupMembers({
        group_id: studentInfo.value.group_id
      });
      groupMembers.value = groupMembersRes.content;
    }
    
    // 设置默认时间范围并加载数据
    setTimeRange('month');
  } catch (err) {
    console.error('初始化数据失败:', err);
    errorMsg.value = '获取基本信息失败，请刷新页面重试';
    loading.value = false;
  }
};

// 监听日期范围变化
watch(dateRange, (newVal) => {
  if (newVal.length === 2) {
    fetchDataByDateRange();
  }
});

// 页面挂载时初始化
onMounted(async() => {
    dateRange.value = setTimeRange('week')
    initCharts();
    await initData();
    await fetchDataByDateRange();
});
</script>

<style scoped>
.student-profile-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  width: 1200px;
  margin: 0 auto;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.time-filter {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
  width: 800px;
}

.time-buttons {
  display: flex;
  gap: 5px;
}

.time-buttons .el-button.active {
  background-color: #409eff;
  color: white;
}

.profile-card, .group-card, .chart-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.profile-info {
  padding: 20px;
}

.avatar-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.avatar {
  background: linear-gradient(135deg, #4158D0 0%, #C850C0 50%, #FFCC70 100%);
  font-size: 36px;
  color: white;
}

.info-item {
  display: flex;
  margin-bottom: 12px;
  line-height: 1.8;
}

.label {
  width: 100px;
  color: #606266;
  font-weight: 500;
}

.value {
  flex: 1;
  color: #303133;
}

.performance-points {
  color: #409eff;
  font-weight: bold;
}

.no-group {
  text-align: center;
  padding: 20px;
  color: #909399;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.group-info {
  padding: 10px 0;
}

.group-members {
  margin-top: 10px;
  max-height: 200px;
  overflow-y: auto;
}

.member-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 10px;
  border-bottom: 1px solid #f5f5f5;
}

.member-item:last-child {
  border-bottom: none;
}

.member-info {
  display: flex;
  flex-direction: column;
}

.member-name {
  font-weight: 500;
}

.member-id {
  font-size: 12px;
  color: #606266;
}

.chart-container {
  width: 100%;
  height: 240px;
}

.exam-chart-container {
  width: 100%;
  height: 250px;
}

.el-card__header {
  background-color: #f5f7fa;
  font-weight: 600;
}

.el-divider {
  margin: 10px 0;
}

.chart {
  width: 100%;
  height: calc(100% - 30px);
}
</style>